<?php

namespace app\admin\controller;

use app\admin\model\Avator as ModelAvator;
use app\admin\model\User;
use app\common\LogService;
use app\common\Notification;
use think\facade\Db;

class Avator  extends Base
{
    public function index()
    {
        return view();
    }
    public function list()
    {
        $limit = input('limit',10);
        $list = ModelAvator::paginate($limit);
        return success($list);
    }
    /**
     * 审核头像（支持单个或批量审核）
     * @param int|null $id 可选参数，如提供则审核单个头像，否则审核所有未审核头像
     * @return mixed
     */
    public function examineAll($id = null)
    {
        // 单个审核
        if ($id !== null) {
            $av = ModelAvator::where(['id' => $id]);
            $avator = $av->find();
            $av->update(['status' => 1]);
            Notification::send($avator['user_id'], '你上传的头像已通过审核');
            $res = User::where(['id' => $avator['user_id']])->update(['avator' => $avator['avator']]);

            LogService::record(
                user_id: getUid(),
                name: '单个审核头像',
                target_id: $id,
                user_type: 2
            );

            return $res ? success() : error();
        }

        // 批量审核
        $res = ModelAvator::where(['status' => 0])->select();
        foreach ($res as $k => $v) {
            Db::startTrans();
            try {
                User::where(['id' => $v['user_id']])->update(['avator' => $v['avator']]);
                ModelAvator::where(['id' => $v['id']])->update(['status' => 1]);
                // 为每个批量审核的用户发送通知
                Notification::send($v['user_id'], '你上传的头像已通过审核');

                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
        }

        // 记录批量审核的操作日志
        LogService::record(
            user_id: getUid(),
            name: '批量审核头像',
            content: ['target' =>  $id],
            user_type: 2
        );

        return success();
    }
    public function del($id)
    {
        $ids = explode(',', $id);
        $res = ModelAvator::destroy($ids);
        LogService::record(
            user_id:$this->uid,
            name: '删除头像',
            target_id: $id,
            user_type: 2
        );
        if ($res) return success();
        return error();
    }
}
